//
//  CADisplayLink+LBHelper.m
//  LBHorizontalTextLoopView
//
//  Created by Apple on 2021/9/20.
//

#import "CADisplayLink+LBHelper.h"

@interface CADisplayLinkTarget : NSObject

@property (nonatomic, weak) id actionTarget;
@property (nonatomic, assign) SEL actionSelector;
@property (nonatomic, copy) void(^actionBlock)(CADisplayLink *displayLink);

@end

@implementation CADisplayLinkTarget

- (instancetype)initWithSelector:(SEL)actionSelector target:(id)actionTarget
{
    self = [super init];
    if (self) {
        self.actionBlock = nil;
        self.actionTarget = actionTarget;
        self.actionSelector = actionSelector;
    }
    return self;
}

- (instancetype)initWithBlock:(void(^)(CADisplayLink *displayLink))actionBlock target:(id)actionTarget
{
    self = [super init];
    if (self) {
        self.actionBlock = actionBlock;
        self.actionTarget =actionTarget;
    }
    return self;
}

- (void)displayLinkAction:(CADisplayLink *)displayLink
{
    if (!self.actionTarget) {
        [displayLink invalidate];
        displayLink = nil;
    } else {
        if (self.actionBlock) {
            self.actionBlock(displayLink);
        }else{
            IMP imp = [self.actionTarget methodForSelector:self.actionSelector];
            void (*func)(id, SEL,CADisplayLink *) = (void *)imp;
            func(self.actionTarget, self.actionSelector,displayLink);
        }
    }
}

@end


@implementation CADisplayLink (LBHelper)

+ (CADisplayLink *)lb_displayLinkWithTarget:(id)target
                                   selector:(SEL)selector
{
    CADisplayLinkTarget *displayLinkTarget = [[CADisplayLinkTarget alloc] initWithSelector:selector target:target];
    CADisplayLink *displayLink = [CADisplayLink displayLinkWithTarget:displayLinkTarget selector:@selector(displayLinkAction:)];
    return displayLink;
}

+ (CADisplayLink *)lb_displayLinkWithTarget:(id)target
                                      block:(void(^)(CADisplayLink *displayLink))block
{
    CADisplayLinkTarget *displayLinkTarget = [[CADisplayLinkTarget alloc] initWithBlock:block target:target];
    CADisplayLink *displayLink = [CADisplayLink displayLinkWithTarget:displayLinkTarget selector:@selector(displayLinkAction:)];
    return displayLink;
}


@end
